package com.tanhua.server.service;

import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendCode(String phone) {
//        //1. 生成随机验证码
//        String code = RandomStringUtils.randomNumeric(6);
//        //2. 调用阿里云发送验证码
//        smsTemplate.sendSms(phone, code);
        String code ="123456";
        //3. 将验证码保存到redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }

    /**
     * 登录校验
     *
     * @param mobile
     * @param code
     * @return
     */
    public Map loginVerification(String mobile, String code) {
        //1. 从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);

        //2. 校验验证码
        if (StringUtils.isEmpty(code) || !code.equals(redisCode)) {
            throw new RuntimeException("验证码校验失败");
        }
        //比对通过 , 删除验证码
        redisTemplate.delete("CHECK_CODE_" + mobile);

        //3. 判断用户是否注册
        boolean isNew = false;
        User user = userApi.findByMobile(mobile);
        if (user == null) {
            user = new User();
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
        }

        //4. 登录成功, 生成token
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", mobile);
        String token = JwtUtils.getToken(tokenMap);

        //5. 封装数据返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);

        return result;
    }
}
